package cn.lijiancn01.demo.system.codegen;

import freemarker.template.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.util.Map;
import java.util.UUID;

@Slf4j
public class MyFreemarkerTemplate implements MyTemplate {
    final Marker marker = MarkerFactory.getMarker("MyFreemarkerTemplate");

    private Configuration cf = new Configuration(Configuration.VERSION_2_3_32);

    @Override
    public String processTemplateIntoString(String templateContent, Map<String, Object> params) {
        try {
            if (StringUtils.isBlank(templateContent)) {
                return "";
            }
            freemarker.template.Template template = new freemarker.template.Template(UUID.randomUUID().toString(), templateContent, cf);
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
            return text.replaceAll(",\n}", "\n}").replaceAll(",\n  }", "\n  }");
        } catch (Exception e) {
            log.error(marker, "processTemplateIntoString error", e);
            return e.getMessage();
        }
    }
}
